'use strict'

define(['zepto', 'ctx', 'sui'], function($, ctx) {
  return {
    init: function() {
      $.init();
      this.parameters = [];
      this.clickNextBtn();
    },

    initSubmit: function(parameters,loadUrl) {
      
      var that = this;

      
      $.ajax({
        type: 'POST',
        url: ctx.marketHost + 'api/taste/bmi-question',
        data: parameters,
        success: function(data){
          var data = JSON.parse(data);
          if(data.code == '0') {
            $.hidePreloader();
            that.questionId = data.data.bmiQuestionId;
            $.toast(data.message);
            $.router.load(loadUrl);
            $(".survery-success").attr("href",ctx.marketHost + "taste/sign-up?bmiQuestionId=" + that.questionId)
          }

        },
        error: function(data){
          $.hidePreloader();
          $.toast(data.message);
        }
      })
    },

    clickNextBtn: function() {
      var that = this;
      $(document).on("click", ".questionnaire-form .survey-btn", function(e) {
        e.preventDefault();
        var sweetDescription = $("input[name='sweetDescription']:checked").val();
        var sweatDescription = $("input[name='sweatDescription']:checked").val();
        var skinDescription = $("input[name='skinDescription']:checked").val();
        var shinDescription = $("input[name='shinDescription']:checked").val();
        if(!sweetDescription || !sweatDescription || !skinDescription || !shinDescription) {
          $.toast("请您做完问券调查题");
          return false;
        } else {
          that.parameters = $(".questionnaire-form").serializeArray()
          $.router.load($(e.currentTarget).data("href"));
        }
      })

      $(document).on("click", ".survey-form .survey-btn", function(e) {
        e.preventDefault();
        var waistDescription = $("input[name='waistDescription']:checked").val();
        var slimDescription = $("input[name='slimDescription']:checked").val();
        var weightDescription = $("input[name='weightDescription']:checked").val();

        if(!waistDescription || !slimDescription || !weightDescription) {
          $.toast("请您做完问券调查题");
          return false;
        } else {
          var surveyFormArray = $(".survey-form").serializeArray();
          that.parameters = that.parameters.concat(surveyFormArray);

          $.router.load($(e.currentTarget).data("href"));
        }
      })

      $(document).on("click", ".information-form .survey-btn", function(e) {
        e.preventDefault();
        $.showPreloader('加载中');
        if(that.informationValidate()) {
          var informationFromArray = $(".information-form").serializeArray(); 
          that.parameters = that.parameters.concat(informationFromArray)
         
          var score = that.calculateBmi().toFixed(1);
          $(".fs-score").html(score);

          if(score <= 19) {
            $("img.result-image").attr('src','static/images/bmi-test/result-1.png');
          }else if(score > 19 && score <= 23.9) {
            $("img.result-image").attr('src','static/images/bmi-test/result-2.png');
          } else if(score > 23.9 && score <=27) {
            $("img.result-image").attr('src','static/images/bmi-test/result-3.png');
          } else {
            $("img.result-image").attr('src','static/images/bmi-test/result-4.png');
          }

          that.parameters.push({name: 'source', value: that.getParameterByName('source')});
          that.initSubmit(that.parameters, $(e.currentTarget).data("href"));
        }


      })
    },

    calculateBmi: function() {
      //Obtain user inputs
      var height=Number($("input[name='height']").val());
      var weight=Number($("input[name='weight']").val());
      
      if(height && weight) {
        //Perform calculation
        var BMI=weight/Math.pow((height / 100),2);
        return BMI;
      }else {
        return 0;
      }
    },

    informationValidate: function() {
      var gender = $("input[name='gender']:checked").val();
      var ages = $("input[name='age']").val().trim();
      var height = $("input[name='height']").val().trim();
      var weight = $("input[name='weight']").val().trim();
      var targetWeight = $("input[name='targetWeight']").val().trim();

      if(!gender) {
        $.toast("请选择性别");
        return false;
      } else if(!ages) {
        $.toast("请填写您的年龄");
         return false;
      } else if(!height) {
         $.toast("请填写您的身高");
         return false;
      } else if(height > 230 || height < 100) {
         $.toast("抱歉，您的身高未在测试范围 100-230cm");
         return false;
      } else if(!weight) {
         $.toast("请填写您的体重 ");
         return false;
      } else if(weight> 200 || weight < 30) {
        $.toast("抱歉，您的体重未在测试范围 30-200kg");
         return false;
      } else if(!targetWeight) {
         $.toast("请填写您的目标体重 ");
         return false;
      } else if(targetWeight > 200 || targetWeight < 30) {
        $.toast("抱歉，您的目标体重未在测试范围 30-200kg");
         return false;
      } else {
        return true;
      }
    },

    getParameterByName: function(name) {
      var url = window.location.href;
      name = name.replace(/[\[\]]/g, "\\$&");
      var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
      results = regex.exec(url);
      if (!results) return null;
      if (!results[2]) return '';
      return decodeURIComponent(results[2].replace(/\+/g, " "));
    }

  }
})
